﻿using Shop.Model.Category;
using Shop.Model.DB;
using Shop.Model.FrontCategory;
using Shop.Repository.LinqHelper;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.SqlSugar;

namespace Shop.Repository.lmpl
{
    internal class FrontCategoryRepository : ShopBaseRepository<DBFrontCategory, long>, IFrontCategoryRepository
    {
        public FrontCategoryRepository (ISqlClientFactory factory) : base(factory)
        {
        }
        public Result[] Gets<Result> (FrontCategoryGet param) where Result : class, new()
        {
            return base.Gets<Result>(param.ToWhere(), "Sort");
        }
        public void Enable (long[] ids)
        {
            if (!base.Update(a => a.IsEnable == true, a => ids.Contains(a.Id)))
            {
                throw new ErrorException("shop.front.category.enable.fail");
            }
        }
        public void SetSort (Dictionary<long, int> sorts)
        {
            if (!base.Update(sorts.ConvertAll(a => new DBFrontCategory
            {
                Id = a.Key,
                Sort = a.Value
            }), "Sort"))
            {
                throw new ErrorException("shop.front.category.update.fail");
            }
        }
        public void Add (DBFrontCategory add)
        {
            add.Id = IdentityHelper.CreateId();
            base.Insert(add);
        }
        public void Stop (long[] ids)
        {
            if (!base.Update(a => a.IsEnable == false, a => ids.Contains(a.Id)))
            {
                throw new ErrorException("shop.front.category.stop.fail");
            }
        }
        public void Move (long id, CategoryMoveArg arg, SubCategorySet[] sets)
        {
            if (sets.IsNull())
            {
                if (!base.Update(arg, a => a.Id == id))
                {
                    throw new ErrorException("shop.front.category.update.fail");
                }
                return;
            }
            ISqlQueue<DBFrontCategory> queue = base.BeginQueue();
            queue.Update(arg, a => a.Id == id);
            queue.Update(sets, "LevelCode", "Lvl");
            _ = queue.Submit();
        }
    }
}
